package com.example.app.ui.connect;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.app.MainActivity;
import com.example.app.R;
import com.example.app.adapter.DeviceAdapter;
import com.example.app.model.BluetoothDeviceModel;
import com.example.app.model.ChatMessage;
import com.example.app.ui.chat.ChatViewModel;
import com.example.app.utils.DeepSeekClient;
import com.example.app.utils.XunfeiTranscription;
import com.google.android.material.button.MaterialButton;

import org.concentus.OpusDecoder;
import org.concentus.OpusException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * 蓝牙连接页面Fragment
 * 负责扫描和连接蓝牙设备
 */
public class ConnectFragment extends Fragment implements DeviceAdapter.OnDeviceClickListener {
    private static final String TAG = "ConnectFragment";
    private static final int SAMPLE_RATE = 16000; // 16K采样率
    private static final int REQUEST_ENABLE_BT = 1;
    private static final int REQUEST_PERMISSIONS = 2;

    // OTA相关常量
    private static final int ELPT_NONE = 0xFF;
    private static final int ELPT_QUERY_SS = 0x0;
    private static final int ELPT_OTA_RESET = 0x02;
    private static final int ELPT_OTA_PACKET = 0x03;
    private static final int ELPT_OP_ENABLE_DFU_MODE = 0x01;

    private static final String[] REQUIRED_PERMISSIONS = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT
    };
    private static final long SCAN_PERIOD = 10000; // 10秒扫描时间
    private static final String DEVICE_NAME_PREFIX = "Lenovo";
    private static final String OTA_BASE_URL = "https://dev.picasau.com";

    // 蓝牙相关常量
    private static final UUID SERVICE_UUID = UUID.fromString("C1D02500-2D20-400A-95D2-6A2F7BCA0C25");
    private static final UUID VOICE_CHAR_UUID = UUID.fromString("C1D02505-2D20-400A-95D2-6A2F7BCA0C25");
    private static final UUID WRITE_CHAR_UUID = UUID.fromString("C1D02505-2D20-400A-95D2-6A2F7BCA0C25");  // 使用相同的UUID
    private static final UUID CLIENT_CHAR_CONFIG = UUID.fromString("00002A4D-0000-1000-8000-00805F9B34FB");
    // 00002902-0000-1000-8000-00805f9b34fb
    // 添加音量放大相关常量和变量
    private static final String PREF_NAME = "LenovoRingPrefs";
    private static final String PREF_AMPLIFICATION_FACTOR = "amplificationFactor";
    private static final String PREF_AUTO_GAIN_CONTROL = "autoGainControl";
    private static final String PREF_LAST_CONNECTED_DEVICE = "lastConnectedDevice";  // 添加新的偏好设置键
    private static final String PREF_LAST_CONNECTED_NAME = "lastConnectedName";      // 添加新的偏好设置键
    private static final float DEFAULT_AMPLIFICATION_FACTOR = 5.0f;
    private float currentAmplificationFactor = DEFAULT_AMPLIFICATION_FACTOR;
    private boolean autoGainControlEnabled = true;

    // UI组件
    private MaterialButton searchButton;
    private RecyclerView deviceList;
    private DeviceAdapter deviceAdapter;
    private List<BluetoothDeviceModel> devices = new ArrayList<>();
    private TextView connectionStatusText;

    // 蓝牙相关变量
    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothLeScanner bluetoothLeScanner;
    private BluetoothGatt bluetoothGatt;
    private boolean scanning = false;
    private Handler handler = new Handler();
    private boolean isReceiverRegistered = false;

    // 添加科大讯飞API Keys成员变量
    private String xunfeiAppId;
    private String xunfeiApiKey;
    private String xunfeiApiSecret;

    // 添加以下变量来跟踪语音数据
    private boolean isVoiceBegin = false;
    private boolean isVoiceEnd = false;
    private List<byte[]> voiceData = new ArrayList<>();
    private int totalBytes = 0;

    // 添加文件输出流用于保存音频数据
    private FileOutputStream voiceFileOutput = null;
    private File recordingsDir;
    private String currentRecordingPath;

    OpusDecoder decoder;

    private AudioTrack audioTrack;

    // 命令类型常量
    private static final byte CMD_QUERY_SS = 0x00;        // 同步时间
    private static final byte CMD_MOUSE_DPI = 0x25;       // 查询设置DPI
    private static final byte CMD_QUERY_FW_INFO = 0x1E;   // 查询版本信息
    private static final byte CMD_QUERY_BATTERY = 0x00;   // 查询电量（通过同步时间命令返回）

    // 添加设备信息跟踪变量
    private int currentHwVer = 0;
    private int currentFwVer = 0;
    private int currentBattery = 0;
    private int currentDpi = 0;
    private String deviceName = null;

    // OkHttpClient 实例用于网络请求
    private OkHttpClient okHttpClient;

    private int ota_data_len = 0;
    private long ota_bin_crc = 0;
    private byte[] ota_data_buff = null;
    private ByteBuffer ota_data_buff_view = null;
    private int ota_data_offset = 0;
    private int ota_c_state = ELPT_NONE; // ELPT_NONE
    private int fsize = 96;
    private Handler mainHandler = new Handler(Looper.getMainLooper());

    // OTA 进度对话框
    private ProgressDialog mOtaProgressDialog;

    // 扫描回调
    private final ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            BluetoothDevice device = result.getDevice();
            if (device != null) {
                String deviceName = device.getName();
                // 只处理以Lenovo开头的设备
                Log.i(TAG, "设备名称:" + deviceName + ", MAC地址:" + device.getAddress());
                if (deviceName != null && deviceName.startsWith(DEVICE_NAME_PREFIX)) {
                    Log.d(TAG, "发现设备: " + deviceName + " (" + device.getAddress() + ")");

                    // 检查设备是否已经存在
                    boolean deviceExists = false;
                    for (BluetoothDeviceModel existingDevice : deviceAdapter.getDevices()) {
                        if (existingDevice.getAddress().equals(device.getAddress())) {
                            deviceExists = true;
                            break;
                        }
                    }

                    // 如果设备不存在，则添加到列表
                    if (!deviceExists) {
                        deviceAdapter.addDevice(new BluetoothDeviceModel(
                                deviceName,
                                device.getAddress(),
                                result.getRssi()
                        ));
                    }
                }
            }
        }

        @Override
        public void onScanFailed(int errorCode) {
            Log.e(TAG, "扫描失败，错误码: " + errorCode);
            switch (errorCode) {
                case SCAN_FAILED_ALREADY_STARTED:
                    Log.e(TAG, "扫描已经启动");
                    break;
                case SCAN_FAILED_APPLICATION_REGISTRATION_FAILED:
                    Log.e(TAG, "应用注册失败");
                    break;
                case SCAN_FAILED_FEATURE_UNSUPPORTED:
                    Log.e(TAG, "设备不支持BLE扫描");
                    break;
                case SCAN_FAILED_INTERNAL_ERROR:
                    Log.e(TAG, "内部错误");
                    break;
                default:
                    Log.e(TAG, "未知错误");
                    break;
            }
        }
    };

    // GATT回调
    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothGatt.STATE_CONNECTED) {
                Log.i(TAG, "已连接到GATT服务器");
                gatt.discoverServices();
                // 更新连接状态
                if (getActivity() instanceof MainActivity) {
                    ((MainActivity) getActivity()).setBluetoothGatt(gatt);
                    ((MainActivity) getActivity()).onConnectionStateChanged(true, deviceName);
                }
            } else if (newState == BluetoothGatt.STATE_DISCONNECTED) {
                Log.i(TAG, "已断开GATT服务器连接");
                updateConnectionStatus(false, null);
                // 重置设备信息
                currentHwVer = 0;
                currentFwVer = 0;
                currentBattery = 0;
                currentDpi = 0;
                deviceName = null;
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "找到服务!");
                BluetoothGattService service = gatt.getService(SERVICE_UUID);
                if (service != null) {
                    // 设置通知
                    BluetoothGattCharacteristic notifyCharacteristic = service.getCharacteristic(VOICE_CHAR_UUID);
                    if (notifyCharacteristic != null) {
                        Log.i(TAG, "找到通知特征!");
                        enableNotification(gatt, notifyCharacteristic);

                        // 初始化writeCharacteristic
                        if (getActivity() instanceof MainActivity) {
                            ((MainActivity) getActivity()).initializeWriteCharacteristic();
                        }

                        // 使用主线程的Handler延迟发送命令
                        if (getActivity() != null) {
                            getActivity().runOnUiThread(() -> {
                                new Handler().postDelayed(() -> {
                                    // 同步时间（包含版本和电量信息）
                                    syncTime();
                                    // 查询DPI
                                    queryDpi();
                                }, 500);  // 延迟2秒
                            });
                        }
                    }
                }
            } else {
                Log.w(TAG, "服务发现失败，状态码: " + status);
            }
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            byte[] data = characteristic.getValue();
            Log.i(TAG, "收到数据，长度: " + data.length);


            switch (data[0]) {
                case ELPT_QUERY_SS: {
                    // 从字节数组中读取各种数据
                    int fw_ver_num = ((data[6] & 0xFF) << 24) | ((data[5] & 0xFF) << 16) |
                               ((data[4] & 0xFF) << 8) | (data[3] & 0xFF);
                    int hw_ver_num = ((data[10] & 0xFF) << 24) | ((data[9] & 0xFF) << 16) |
                               ((data[8] & 0xFF) << 8) | (data[7] & 0xFF);
                    int battery_level_p = data[11] & 0xFF;
                    int sys_st_duf_flag = data[12] & 0xFF;
                    int ble_mtu = ((data[14] & 0xFF) << 8) | (data[13] & 0xFF);
                    long ota_bin_crc32 = ((data[18] & 0xFFL) << 24) | ((data[17] & 0xFFL) << 16) |
                                   ((data[16] & 0xFFL) << 8) | (data[15] & 0xFFL);
                    int ota_bin_offset = ((data[22] & 0xFF) << 24) | ((data[21] & 0xFF) << 16) |
                                   ((data[20] & 0xFF) << 8) | (data[19] & 0xFF);

                    Log.i(TAG, String.format("收到同步时间响应: 硬件版本=%d, 固件版本=%d, 电量=%d%%, DFU标志=%d, MTU=%d, OTA偏移=%d, OTA CRC32=%X",
                            hw_ver_num, fw_ver_num, battery_level_p, sys_st_duf_flag, ble_mtu, ota_bin_offset, ota_bin_crc32));

                    currentBattery = battery_level_p;
                    currentFwVer = fw_ver_num;
                    currentHwVer = hw_ver_num;

                    // 更新MainActivity中的DPI值
                    if (getActivity() instanceof MainActivity) {
                        ((MainActivity) getActivity()).onDeviceInfoReceived(
                                currentHwVer, currentFwVer, currentBattery, currentDpi);
                    }


                    switch (ota_c_state) {
                        case ELPT_NONE: {
                            Log.i(TAG, String.format("MTU: %d, SV: %d, HV: %d, Power: %d, DFU: %d",
                                    ble_mtu, fw_ver_num, hw_ver_num, battery_level_p, sys_st_duf_flag));
                            break;
                        }
                        case ELPT_QUERY_SS: {
                            Log.i(TAG, String.format("MTU: %d, SV: %d, HV: %d, Offset: %d, CRC32: %X",
                                    ble_mtu, fw_ver_num, hw_ver_num, ota_bin_offset, ota_bin_crc32));
                            fsize = ble_mtu;

                            if (ota_bin_crc == ota_bin_crc32) {
                                Log.i(TAG, "继续升级");
                                ota_c_state = ELPT_OTA_PACKET;
                                ota_data_offset = ota_bin_offset;
                                doSendOTAFrame();
                            } else {
                                Log.i(TAG, "开始升级");
                                ota_c_state = ELPT_OTA_RESET;
                                doOTAReset();
                            }
                            break;
                        }
                        case ELPT_OTA_RESET: {
                            Log.i(TAG, "开始升级");
                            ota_c_state = ELPT_OTA_PACKET;
                            doSendOTAFrame();
                            break;
                        }
                        case ELPT_OTA_PACKET: {
                            // Log.i(TAG, "next frame -> " + ota_bin_offset);
                            // ota_data_offset = ota_bin_offset; // 应该在发送前设置

                            // 更新对话框进度
                            if (getActivity() != null && !getActivity().isFinishing()) {
                                final int currentProgress;
                                if (ota_data_len > 0) {
                                    // ota_bin_offset 是设备期望的下一个包的起始，所以到此为止的数据已确认收到
                                    currentProgress = (int) (((long)ota_bin_offset * 100) / ota_data_len);
                                } else {
                                    currentProgress = 0;
                                }
                                final String progressMessage = "正在升级: " + Math.min(currentProgress, 100) + "%";
                                getActivity().runOnUiThread(() -> {
                                    if (mOtaProgressDialog != null && mOtaProgressDialog.isShowing()) {
                                        mOtaProgressDialog.setProgress(Math.min(currentProgress, 100));
                                        mOtaProgressDialog.setMessage(progressMessage);
                                        Log.i(TAG, "Dialog progress: " + currentProgress + "%"); // 添加日志确认进度更新
                                    }
                                });
                            }

                            if (ota_bin_crc32 == 0x0) {
                                Log.i(TAG, "ota success");
                                if (getActivity() != null && !getActivity().isFinishing()) {
                                    getActivity().runOnUiThread(() -> {
                                        if (mOtaProgressDialog != null && mOtaProgressDialog.isShowing()) {
                                            mOtaProgressDialog.setProgress(100);
                                            mOtaProgressDialog.setMessage("升级成功！设备将自动断开连接。");
                                            new Handler(Looper.getMainLooper()).postDelayed(() -> {
                                                if (mOtaProgressDialog != null && mOtaProgressDialog.isShowing()) {
                                                    mOtaProgressDialog.dismiss();
                                                }
                                                disconnectDevice(); // 在对话框关闭后断开连接
                                            }, 1500); // 显示成功消息1.5秒
                                        } else {
                                            disconnectDevice(); // 对话框未显示，直接断开
                                        }
                                    });
                                } else {
                                    disconnectDevice(); // Activity不存在，直接断开
                                }
                                ota_c_state = ELPT_NONE; // 成功后也重置状态
                                return; // 结束OTA处理
                            } else if (ota_bin_crc32 == 0xFFFFFFFF) {
                                Log.e(TAG, "ota failure from device");
                                handleOtaFailure("升级失败（设备报告错误）。", false);
                                return; // 结束OTA处理
                            } else {
                                // 准备发送下一帧数据
                                final int nextOffset = ota_bin_offset;
                                new Handler(Looper.getMainLooper()).postDelayed(() -> {
                                    if (ota_c_state == ELPT_OTA_PACKET) { // 再次检查状态，防止中途被中止
                                        ota_data_offset = nextOffset;
                                        doSendOTAFrame();
                                    }
                                }, 50); // 当前延迟50毫秒 太快容易失败
                            }
                            break;
                        }
                    }
                    break;
                }
                case ELPT_OP_ENABLE_DFU_MODE: {
//                    Log.i(TAG, "设备允许进入OTA模式，准备开始升级流程...延迟2秒执行doQueryState");
//                    // 延迟5秒后发送查询状态命令
//                    mainHandler.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            doQueryState();
//                        }
//                    }, 2000);
                    Log.i(TAG, "设备允许进入OTA模式，准备开始升级流程...");
                    // 直接开始OTA重置流程，而不是查询状态
                    ota_c_state = ELPT_OTA_RESET;
                    doOTAReset();
                    break;
                }
                case 0x23: {
                    if (data[3] == 0x01) {
                        Log.i(TAG, "------------------------------Voice Begin---------------------------------");
                        isVoiceBegin = true;
                        isVoiceEnd = false;
                        totalBytes = 0;
                        voiceData.clear();
                    } else {
                        Log.i(TAG, "------------------------------Voice End---------------------------------");
                        isVoiceEnd = true;
                        if (totalBytes > 0) {
                            Log.i(TAG, "准备上传音频数据，大小: " + totalBytes + " 字节");

                            byte[] audioData = new byte[totalBytes];
                            int position = 0;
                            for (byte[] chunk : voiceData) {
                                System.arraycopy(chunk, 0, audioData, position, chunk.length);
                                position += chunk.length;
                            }

                            // 保存原始PCM为WAV文件
                            String originalWavFilePath = savePcmAsWav(audioData);
                            if (originalWavFilePath != null) {
                                if (getActivity() != null) {
                                    getActivity().runOnUiThread(() -> {
                                        Toast.makeText(getContext(), "原始录音已保存至: " + originalWavFilePath, Toast.LENGTH_SHORT).show();
                                    });
                                }
                            }

                            // 确定放大系数
                            float factorToUse = currentAmplificationFactor;
                            if (autoGainControlEnabled) {
                                factorToUse = calculateAutoGainFactor(audioData);
                            }
                            Log.i(TAG, "使用放大系数: " + factorToUse + (autoGainControlEnabled ? " (自动)" : " (手动)"));

                            // 放大音频数据
                            byte[] amplifiedAudioData = amplifyPcmAudio(audioData, factorToUse);

                            // 保存放大后的PCM为WAV文件
                            String amplifiedWavFilePath = savePcmAsWav(amplifiedAudioData, "amplified_recording");
                            if (amplifiedWavFilePath != null) {
                                final float finalFactor = factorToUse;
                                if (getActivity() != null) {
                                    getActivity().runOnUiThread(() -> {
                                        Toast.makeText(getContext(),
                                                "放大后的录音(x" + String.format("%.1f", finalFactor) + ")已保存",
                                                Toast.LENGTH_SHORT).show();
                                    });
                                }
                            }

                            // 使用放大后的音频数据进行转写
                            if (!xunfeiAppId.isEmpty() && !xunfeiApiKey.isEmpty() && !xunfeiApiSecret.isEmpty()) {
                                XunfeiTranscription transcription = new XunfeiTranscription(xunfeiAppId, xunfeiApiKey, xunfeiApiSecret);
                                transcription.setCallback(new XunfeiTranscription.TranscriptionCallback() {
                                    @Override
                                    public void onTranscriptionStart() {
                                        if (getActivity() != null) {
                                            getActivity().runOnUiThread(() -> {
                                                Toast.makeText(getContext(), "开始转写...", Toast.LENGTH_SHORT).show();
                                            });
                                        }
                                    }

                                    @Override
                                    public void onTranscriptionProgress(String message) {
                                        if (getActivity() != null) {
                                            getActivity().runOnUiThread(() -> {
                                                Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
                                            });
                                        }
                                    }

                                    @Override
                                    public void onTranscriptionComplete(String result) {
                                        handleTranscriptionResult(result);
                                    }

                                    @Override
                                    public void onTranscriptionError(String error) {
                                        if (getActivity() != null) {
                                            getActivity().runOnUiThread(() -> {
                                                Toast.makeText(getContext(), "转写失败: " + error, Toast.LENGTH_LONG).show();
                                            });
                                        }
                                    }
                                });

                                transcription.startTranscriptionWithData(amplifiedAudioData);
                            }

                            // 重置状态
                            isVoiceBegin = false;
                            isVoiceEnd = false;
                            voiceData.clear();
                            totalBytes = 0;
                        }
                    }
                    break;
                }
                case 0x24: {
                    byte[] data_packet = new byte[80];
                    short[] pcm = new short[320];
                    if (isVoiceBegin && !isVoiceEnd) {
                        Log.i(TAG, "结束语音");

                        // 收集PCM数据
                        try {
                            if (data.length == 243) {
                                for (int i = 0; i < 3; i++) {
                                    System.arraycopy(data, (i * 80) + 3, data_packet, 0, data_packet.length);
                                    try {
                                        int samplesDecoded = decoder.decode(data_packet, 0, data_packet.length, pcm, 0, 320, false);
                                    } catch (OpusException e) {
                                        throw new RuntimeException(e);
                                    }
                                    byte[] bytesOut = ShortsToBytes(pcm);

                                    // 保存PCM数据用于上传到讯飞
                                    voiceData.add(bytesOut);
                                    totalBytes += bytesOut.length;

                                    // 播放PCM数据
                                    if (audioTrack != null && audioTrack.getState() == AudioTrack.STATE_INITIALIZED) {
                                        audioTrack.play();
                                        audioTrack.write(bytesOut, 0, bytesOut.length);
                                        Log.i(TAG, "Play Frame Len: " + String.valueOf(bytesOut.length));
                                    }
                                }
                            }
                        } catch (Exception e) {
                            Log.e(TAG, "解码或播放音频数据时出错", e);
                        }
                    }
                    break;
                }
                case 0x25: {  // ELPT_OP_MOUSE_DPI 响应
                    if (data.length >= 5) {
                        byte dpiStep = data[4];
                        // 计算实际DPI值
                        currentDpi = (int) (dpiStep * 27.8);

                        // 更新MainActivity中的DPI值
                        if (getActivity() instanceof MainActivity) {
                            ((MainActivity) getActivity()).onDeviceInfoReceived(
                                    currentHwVer, currentFwVer, currentBattery, currentDpi);
                        }
                        Log.i(TAG, String.format("收到DPI响应: 步进值=%d, 实际DPI=%d",
                                dpiStep, currentDpi));
                    }
                    break;
                }
                default: {
                    Log.i(TAG, "收到未知命令: 0x" + String.format("%02X", data[0]));
                    break;
                }
            }
        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicWrite(gatt, characteristic, status);
            String uuidStr = characteristic.getUuid().toString();
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "特征 " + uuidStr + " 写入成功 (onCharacteristicWrite)");
            } else {
                Log.w(TAG, "特征 " + uuidStr + " 写入失败 (onCharacteristicWrite), 状态码: " + status);
                // 如果OTA过程中的写入失败，可能需要在这里处理错误，例如停止OTA并通知用户
                if (characteristic.getUuid().equals(WRITE_CHAR_UUID) && ota_c_state != ELPT_NONE) {
                    Log.e(TAG, "OTA数据帧写入操作未成功 (onCharacteristicWrite), status: " + status);
                    // 你可以在这里添加停止OTA或重试的逻辑
                }
            }
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i(TAG, "描述符写入成功");
            } else {
                Log.e(TAG, "描述符写入失败: " + status);
            }
        }

    };

    // 添加以下两个方法到MainActivity类中
    public static byte[] ShortsToBytes(short[] input, int offset, int length) {
        byte[] processedValues = new byte[length * 2];
        for (int c = 0; c < length; c++) {
            processedValues[c * 2] = (byte) (input[c + offset] & 0xFF);
            processedValues[c * 2 + 1] = (byte) ((input[c + offset] >> 8) & 0xFF);
        }

        return processedValues;
    }

    public static byte[] ShortsToBytes(short[] input) {
        return ShortsToBytes(input, 0, input.length);
    }

    // 添加保存WAV文件的方法
    private String savePcmAsWav(byte[] pcmData) {
        return savePcmAsWav(pcmData, "recording");
    }

    // 添加带文件名前缀的重载方法
    private String savePcmAsWav(byte[] pcmData, String filenamePrefix) {
        if (recordingsDir == null || !recordingsDir.exists()) {
            Log.e(TAG, "录音目录不存在");
            return null;
        }

        String timeStamp = new java.text.SimpleDateFormat("yyyyMMdd_HHmmss", java.util.Locale.getDefault()).format(new java.util.Date());
        String wavFileName = filenamePrefix + "_" + timeStamp + ".wav";
        File wavFile = new File(recordingsDir, wavFileName);

        try {
            FileOutputStream out = new FileOutputStream(wavFile);

            // 添加WAV文件头
            writeWavHeader(out, pcmData.length);

            // 写入PCM数据
            out.write(pcmData);
            out.close();

            Log.i(TAG, "WAV文件已保存: " + wavFile.getAbsolutePath());

            // 通知媒体库扫描该文件
            if (getActivity() != null) {
                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(wavFile);
                mediaScanIntent.setData(contentUri);
                getActivity().sendBroadcast(mediaScanIntent);
            }

            return wavFile.getAbsolutePath();

        } catch (Exception e) {
            Log.e(TAG, "保存WAV文件时出错", e);
            return null;
        }
    }

    // 添加写入WAV文件头的方法
    private void writeWavHeader(FileOutputStream out, int pcmDataLength) throws IOException {
        int channelCount = 1; // 单声道
        int bitsPerSample = 16; // 16位
        int bytesPerSample = bitsPerSample / 8;
        int blockAlign = channelCount * bytesPerSample;
        int byteRate = SAMPLE_RATE * blockAlign;
        int totalDataLen = pcmDataLength + 36;

        byte[] header = new byte[44];

        // RIFF头
        header[0] = 'R';  // RIFF/WAVE header
        header[1] = 'I';
        header[2] = 'F';
        header[3] = 'F';
        header[4] = (byte) (totalDataLen & 0xff);
        header[5] = (byte) ((totalDataLen >> 8) & 0xff);
        header[6] = (byte) ((totalDataLen >> 16) & 0xff);
        header[7] = (byte) ((totalDataLen >> 24) & 0xff);
        header[8] = 'W';
        header[9] = 'A';
        header[10] = 'V';
        header[11] = 'E';

        // fmt子块
        header[12] = 'f';
        header[13] = 'm';
        header[14] = 't';
        header[15] = ' ';
        header[16] = 16;  // 4字节：fmt子块的大小（16字节）
        header[17] = 0;
        header[18] = 0;
        header[19] = 0;
        header[20] = 1;   // 音频格式（1表示PCM）
        header[21] = 0;
        header[22] = (byte) channelCount;   // 通道数
        header[23] = 0;
        header[24] = (byte) (SAMPLE_RATE & 0xff);
        header[25] = (byte) ((SAMPLE_RATE >> 8) & 0xff);
        header[26] = (byte) ((SAMPLE_RATE >> 16) & 0xff);
        header[27] = (byte) ((SAMPLE_RATE >> 24) & 0xff);
        header[28] = (byte) (byteRate & 0xff);
        header[29] = (byte) ((byteRate >> 8) & 0xff);
        header[30] = (byte) ((byteRate >> 16) & 0xff);
        header[31] = (byte) ((byteRate >> 24) & 0xff);
        header[32] = (byte) blockAlign;   // 块对齐（每个采样点的字节数）
        header[33] = 0;
        header[34] = (byte) bitsPerSample;  // 每个采样点的位数
        header[35] = 0;

        // data子块
        header[36] = 'd';
        header[37] = 'a';
        header[38] = 't';
        header[39] = 'a';
        header[40] = (byte) (pcmDataLength & 0xff);
        header[41] = (byte) ((pcmDataLength >> 8) & 0xff);
        header[42] = (byte) ((pcmDataLength >> 16) & 0xff);
        header[43] = (byte) ((pcmDataLength >> 24) & 0xff);

        out.write(header, 0, 44);
    }

    /**
     * 蓝牙设备广播接收器
     * 用于接收蓝牙设备搜索的结果
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 当发现蓝牙设备时
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 获取发现的设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 获取信号强度
                int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
                if (device != null) {
                    // 获取设备名称
                    String deviceName = device.getName();
                    // 如果设备名称为空，显示为未知设备
                    if (deviceName == null || deviceName.isEmpty()) {
                        deviceName = "未知设备";
                    }
                    // 只添加以Lenovo开头的设备
                    if (deviceName.startsWith(DEVICE_NAME_PREFIX)) {
                        // 直接连接设备
                        bluetoothGatt = device.connectGatt(getContext(), false, gattCallback);
                    }
                }
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true); // 启用菜单
        // 获取蓝牙管理器
        bluetoothManager = (BluetoothManager) requireContext()
                .getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothManager != null) {
            bluetoothAdapter = bluetoothManager.getAdapter();
        }

        // 创建录音目录
        createRecordingsDirectory();

        // 初始化 Opus 解码器
        try {
            decoder = new OpusDecoder(SAMPLE_RATE, 1); // 16kHz, 单声道
            Log.i(TAG, "Opus 解码器初始化成功");
        } catch (OpusException e) {
            Log.e(TAG, "Opus 解码器初始化失败", e);
        }

        // 初始化 AudioTrack
        int minBufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE,
                AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT);
        audioTrack = new AudioTrack(
                AudioManager.STREAM_MUSIC,
                SAMPLE_RATE,
                AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT,
                minBufferSize,
                AudioTrack.MODE_STREAM
        );
        Log.i(TAG, "AudioTrack 初始化成功，缓冲区大小: " + minBufferSize);

        // 加载保存的放大系数和自动增益控制设置
        loadAmplificationFactor();

        // 在onCreate中加载科大讯飞API Keys
        loadXunfeiApiKeys();

        // 初始化 OkHttpClient
        okHttpClient = new OkHttpClient();
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.top_toolbar_menu, menu);
        // 如果已连接，显示断开按钮，否则隐藏
        MenuItem disconnectItem = menu.findItem(R.id.action_disconnect);
        if (disconnectItem != null) {
            boolean isConnected = bluetoothGatt != null;
            disconnectItem.setVisible(isConnected);
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.action_disconnect) {
            disconnectDevice();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // 添加加载科大讯飞API Keys的方法
    private void loadXunfeiApiKeys() {
        SharedPreferences sharedPreferences = requireContext().getSharedPreferences("AppSettings", Context.MODE_PRIVATE);
        xunfeiAppId = sharedPreferences.getString("xunfei_app_id", "f62d17ec");
        xunfeiApiKey = sharedPreferences.getString("xunfei_api_key", "3b40bc3bc25a0a3b1e0c0cc85558c6a1");
        xunfeiApiSecret = sharedPreferences.getString("xunfei_api_secret", "NzJmMzg2MmRiZDJmNDIiNZA3ZGM1NiM4");

        Log.d(TAG, "加载科大讯飞API密钥:");
        Log.d(TAG, "AppID: " + (xunfeiAppId.isEmpty() ? "未设置" : "已设置"));
        Log.d(TAG, "API Key: " + (xunfeiApiKey.isEmpty() ? "未设置" : "已设置"));
        Log.d(TAG, "API Secret: " + (xunfeiApiSecret.isEmpty() ? "未设置" : "已设置"));

        if (xunfeiAppId.isEmpty() || xunfeiApiKey.isEmpty() || xunfeiApiSecret.isEmpty()) {
            Log.w(TAG, "科大讯飞API Keys未设置，转写功能将不可用");
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "请在设置中配置科大讯飞API Keys", Toast.LENGTH_LONG).show();
                });
            }
        } else {
            Log.i(TAG, "科大讯飞API Keys加载成功");
        }
    }

    // 添加创建录音目录的方法
    private void createRecordingsDirectory() {
        // 使用应用专属目录
        File externalDir = requireContext().getExternalFilesDir(null);
        if (externalDir != null) {
            recordingsDir = new File(externalDir, "Recordings");
            if (!recordingsDir.exists()) {
                boolean success = recordingsDir.mkdirs();
                if (!success) {
                    Log.e(TAG, "无法创建录音目录");
                    if (getActivity() != null) {
                        getActivity().runOnUiThread(() -> {
                            Toast.makeText(getContext(), "无法创建录音目录，录音功能可能不可用", Toast.LENGTH_SHORT).show();
                        });
                } else {
                    Log.i(TAG, "录音目录已创建: " + recordingsDir.getAbsolutePath());
                    }
                }
            }
        } else {
            Log.e(TAG, "无法访问外部存储");
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "无法访问存储空间，录音功能可能不可用", Toast.LENGTH_SHORT).show();
                });
            }
        }
    }

    // 添加音量放大相关方法
    private void loadAmplificationFactor() {
        SharedPreferences prefs = requireContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        currentAmplificationFactor = prefs.getFloat(PREF_AMPLIFICATION_FACTOR, DEFAULT_AMPLIFICATION_FACTOR);
        autoGainControlEnabled = prefs.getBoolean(PREF_AUTO_GAIN_CONTROL, true);
        Log.i(TAG, "当前音量放大系数: " + currentAmplificationFactor + ", 自动增益控制: " + (autoGainControlEnabled ? "开启" : "关闭"));
    }

    private float calculateAudioEnergy(byte[] pcmData) {
        if (pcmData == null || pcmData.length < 2) {
            return 0;
        }

        long sum = 0;
        int samples = 0;

        for (int i = 0; i < pcmData.length; i += 2) {
            short sample = (short) ((pcmData[i] & 0xFF) | ((pcmData[i + 1] & 0xFF) << 8));
            sum += Math.abs(sample);
            samples++;
        }

        float avgEnergy = samples > 0 ? (float) sum / samples : 0;
        float normalizedEnergy = avgEnergy / Short.MAX_VALUE;

        Log.i(TAG, "音频平均能量: " + avgEnergy + ", 归一化能量: " + normalizedEnergy);
        return normalizedEnergy;
    }

    private float calculateAutoGainFactor(byte[] pcmData) {
        float energy = calculateAudioEnergy(pcmData);
        float targetEnergy = 0.5f;

        if (energy < targetEnergy && energy > 0) {
            float factor = targetEnergy / energy;
            factor = Math.min(factor, 15.0f);
            Log.i(TAG, "自动增益调整: 能量=" + energy + ", 目标=" + targetEnergy + ", 放大系数=" + factor);
            return factor;
        } else if (energy <= 0) {
            Log.i(TAG, "检测到静音，使用默认放大系数: " + DEFAULT_AMPLIFICATION_FACTOR);
            return DEFAULT_AMPLIFICATION_FACTOR;
        } else {
            Log.i(TAG, "音量足够大，无需放大");
            return 1.0f;
        }
    }

    private byte[] amplifyPcmAudio(byte[] pcmData, float amplificationFactor) {
        if (pcmData == null || pcmData.length < 2) {
            return pcmData;
        }

        byte[] amplifiedData = new byte[pcmData.length];

        for (int i = 0; i < pcmData.length; i += 2) {
            short sample = (short) ((pcmData[i] & 0xFF) | ((pcmData[i + 1] & 0xFF) << 8));
            float amplifiedSample = sample * amplificationFactor;

            if (amplifiedSample > Short.MAX_VALUE) {
                amplifiedSample = Short.MAX_VALUE;
            } else if (amplifiedSample < Short.MIN_VALUE) {
                amplifiedSample = Short.MIN_VALUE;
            }

            short amplifiedShort = (short) amplifiedSample;
            amplifiedData[i] = (byte) (amplifiedShort & 0xFF);
            amplifiedData[i + 1] = (byte) ((amplifiedShort >> 8) & 0xFF);
        }

        return amplifiedData;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_connect, container, false);

        // 初始化顶部导航栏
        initTopBar();

        // 初始化UI组件
        searchButton = view.findViewById(R.id.btn_search);
        deviceList = view.findViewById(R.id.device_list);

        // 设置搜索按钮点击事件
        searchButton.setOnClickListener(v -> toggleScan());

        // 初始化设备列表
        deviceAdapter = new DeviceAdapter(this);
        deviceList.setLayoutManager(new LinearLayoutManager(getContext()));
        deviceList.setAdapter(deviceAdapter);

        initBluetooth();
        return view;
    }

    /**
     * 初始化顶部导航栏
     */
    private void initTopBar() {
        Activity activity = getActivity();
        if (activity != null) {
            ActionBar actionBar = ((AppCompatActivity) activity).getSupportActionBar();
            if (actionBar != null) {
                actionBar.hide(); // 隐藏 ActionBar
            }
        }
    }

    private void initBluetooth() {
        if (bluetoothManager != null) {
            bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
            if (bluetoothLeScanner == null) {
                Log.e(TAG, "不支持BLE扫描");
                return;
            }
        }

        // 注册蓝牙广播接收器
        if (!isReceiverRegistered) {
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            requireContext().registerReceiver(receiver, filter);
            isReceiverRegistered = true;
        }
    }

    private void toggleScan() {
        if (!scanning) {
            startScan();
        } else {
            stopScan();
        }
    }

    private void startScan() {
        if (bluetoothLeScanner != null && !scanning) {
            // 检查权限
            if (!checkPermissions()) {
                requestPermissions();
                return;
            }

            // 检查蓝牙是否启用
            if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                return;
            }

            scanning = true;
            // 更新按钮状态
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    searchButton.setText("停止搜索");
                    searchButton.setBackgroundTintList(getResources().getColorStateList(R.color.red, null));
                });
            }

            // 设置扫描参数
            ScanSettings settings = new ScanSettings.Builder()
                    .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                    .build();

            // 开始扫描
            bluetoothLeScanner.startScan(null, settings, scanCallback);
            Log.d(TAG, "开始扫描设备");

            // 设置超时自动停止
            handler.postDelayed(this::stopScan, SCAN_PERIOD);
        }
    }

    private void stopScan() {
        if (bluetoothLeScanner != null && scanning) {
            scanning = false;
            bluetoothLeScanner.stopScan(scanCallback);
            handler.removeCallbacksAndMessages(null);
            Log.d(TAG, "停止扫描");

            // 更新按钮状态
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    searchButton.setText("开始搜索");
                    searchButton.setBackgroundTintList(getResources().getColorStateList(R.color.purple_500, null));
                });
            }
        }
    }

    private boolean checkPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12及以上版本需要BLUETOOTH_SCAN和BLUETOOTH_CONNECT权限
            return requireContext().checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED
                    && requireContext().checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
                    && requireContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        } else {
            // Android 12以下版本需要位置权限
            return requireContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    && requireContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        }
    }

    private void requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12及以上版本
            if (requireContext().checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED
                    || requireContext().checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED
                    || requireContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                // 显示权限说明对话框
                new AlertDialog.Builder(requireContext())
                        .setTitle("需要权限")
                        .setMessage("扫描蓝牙设备需要位置权限和蓝牙权限，请在接下来的对话框中授予权限。")
                        .setPositiveButton("确定", (dialog, which) -> {
                            requestPermissions(REQUIRED_PERMISSIONS, REQUEST_PERMISSIONS);
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        } else {
            // Android 12以下版本
            if (requireContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || requireContext().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                // 显示权限说明对话框
                new AlertDialog.Builder(requireContext())
                        .setTitle("需要位置权限")
                        .setMessage("扫描蓝牙设备需要位置权限，请在接下来的对话框中授予权限。")
                        .setPositiveButton("确定", (dialog, which) -> {
                            requestPermissions(REQUIRED_PERMISSIONS, REQUEST_PERMISSIONS);
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSIONS) {
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }

            if (allGranted) {
                startScan();
            } else {
                // 如果用户拒绝了权限，显示设置对话框
                new AlertDialog.Builder(requireContext())
                        .setTitle("权限被拒绝")
                        .setMessage("没有必要的权限，无法扫描蓝牙设备。请在系统设置中手动开启权限。")
                        .setPositiveButton("去设置", (dialog, which) -> {
                            // 打开应用设置页面
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", requireContext().getPackageName(), null);
                            intent.setData(uri);
                            startActivity(intent);
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            if (resultCode == android.app.Activity.RESULT_OK) {
                startScan();
            } else {
                Toast.makeText(getContext(), "需要启用蓝牙才能扫描设备", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void updateConnectionStatus(boolean connected, String deviceName) {
        if (getActivity() != null) {
            getActivity().runOnUiThread(() -> {
                if (getActivity() instanceof MainActivity) {
                    ((MainActivity) getActivity()).onConnectionStateChanged(connected, deviceName);
                }
            });
        }
    }

    private boolean enableNotification(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (getActivity() != null &&
                    getActivity().checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT)
                            != PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "缺少蓝牙连接权限");
                // 请求权限
                requestPermissions(new String[]{
                        Manifest.permission.BLUETOOTH_CONNECT
                }, REQUEST_PERMISSIONS);
                return false;
            }
        }

        // 设置本地通知
        boolean success = gatt.setCharacteristicNotification(characteristic, true);
        Log.i(TAG, "设置特征(" + characteristic.getUuid() + ")通知: " + (success ? "成功" : "失败"));

        if (success) {
            // 写入客户端特征配置描述符
            BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHAR_CONFIG);
            if (descriptor != null) {
                descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                boolean writeResult = gatt.writeDescriptor(descriptor);
                Log.i(TAG, "写入描述符: " + (writeResult ? "成功" : "失败"));
                return writeResult;
            }
        }

        return success;
    }

    @Override
    public void onConnectClick(BluetoothDeviceModel device) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            if (getActivity() != null &&
                    getActivity().checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT)
                            != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        }

        // 停止扫描
        stopScan();

        // 保存设备名称
        deviceName = device.getName();

        BluetoothDevice bluetoothDevice = bluetoothAdapter.getRemoteDevice(device.getAddress());
        bluetoothGatt = bluetoothDevice.connectGatt(getContext(), false, gattCallback);

        // 保存最后连接的设备信息
        saveLastConnectedDevice(device.getAddress(), device.getName());

        // 更新UI状态
        if (getActivity() instanceof MainActivity) {
            ((MainActivity) getActivity()).onConnectionStateChanged(true, deviceName);
        }
    }

    /**
     * 保存最后连接的设备信息
     */
    private void saveLastConnectedDevice(String address, String name) {
        SharedPreferences prefs = requireContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PREF_LAST_CONNECTED_DEVICE, address);
        editor.putString(PREF_LAST_CONNECTED_NAME, name);
        editor.apply();
        Log.i(TAG, "已保存最后连接的设备信息: " + name + " (" + address + ")");
    }

    // 在用户点击断开连接按钮时调用此方法
    public void disconnectDevice() {
        // 如果OTA对话框正在显示，则关闭它
        if (getActivity() != null && !getActivity().isFinishing()) {
            getActivity().runOnUiThread(() -> {
                if (mOtaProgressDialog != null && mOtaProgressDialog.isShowing()) {
                    Log.d(TAG, "disconnectDevice called, dismissing OTA dialog.");
                    mOtaProgressDialog.dismiss();
                }
            });
        }
        // 如果OTA正在进行中被意外断开，重置状态
        if (ota_c_state != ELPT_NONE) {
            Log.w(TAG, "OTA process was active and is now being stopped due to disconnection.");
            ota_c_state = ELPT_NONE;
        }

        if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
            if (bluetoothGatt != null) {
                bluetoothGatt.disconnect();
                bluetoothGatt.close();
                bluetoothGatt = null;
            }
            // 清除最后连接的设备信息
            clearLastConnectedDevice();

            // 更新UI状态 - 切换到主线程
            if (getActivity() != null) {
                getActivity().runOnUiThread(() -> {
                    if (getActivity() instanceof MainActivity) {
                        ((MainActivity) getActivity()).onConnectionStateChanged(false, "");
                    }
                    // 更新连接状态文本
                    if (connectionStatusText != null) {
                        connectionStatusText.setText("连接状态：未连接");
                    }
                    // 启用扫描按钮
                    if (searchButton != null) {
                        searchButton.setEnabled(true);
                    }
                    // 清空设备列表
                    if (deviceAdapter != null) {
                        deviceAdapter.clearDevices();
                    }
                });
            }
            // 清空设备名称
            deviceName = null;
        }
    }

    private void handleTranscriptionResult(String result) {
        Log.d(TAG, "转写结果: " + result);
        if (result != null && !result.isEmpty()) {
            // 获取 ChatViewModel 实例
            ChatViewModel chatViewModel = new ViewModelProvider(requireActivity()).get(ChatViewModel.class);

            // 添加用户消息
            ChatMessage userMessage = new ChatMessage(result, ChatMessage.TYPE_USER);
            chatViewModel.addMessage(userMessage);
            Log.d(TAG, "用户消息已添加到聊天列表");

            // 从 SharedPreferences 获取 DeepSeek API Key
            SharedPreferences sharedPreferences = requireContext().getSharedPreferences("AppSettings", Context.MODE_PRIVATE);
            String deepseekApiKey = sharedPreferences.getString("deepseek_api_key", "");

            if (deepseekApiKey.isEmpty()) {
                Log.d(TAG, "DeepSeek API Key 未设置，显示错误消息");
                // 如果 API Key 未设置，显示错误消息
                ChatMessage errorMessage = new ChatMessage("请在设置中配置 DeepSeek API Key", ChatMessage.TYPE_AI);
                chatViewModel.addMessage(errorMessage);

                // 发送广播
                Intent intent = new Intent("com.example.app.AUDIO_TRANSCRIPTION_RESULT");
                intent.putExtra("transcription_result", result);
                LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(intent);

                // 延迟切换到聊天页面
                new Handler().postDelayed(() -> {
                    if (getActivity() instanceof MainActivity) {
                        ((MainActivity) getActivity()).navigateToChat();
                        Log.d(TAG, "已切换到聊天页面");
                    }
                }, 500);
                return;
            }

            // 创建 DeepSeek 客户端并发送消息
            DeepSeekClient deepSeekClient = new DeepSeekClient(deepseekApiKey);
            deepSeekClient.sendMessage(result, new DeepSeekClient.ResponseCallback() {
                @Override
                public void onStart() {
                    // 添加一个空的AI消息，后续会更新内容
                    ChatMessage aiMessage = new ChatMessage("", ChatMessage.TYPE_AI);
                    chatViewModel.addMessage(aiMessage);
                }

                @Override
                public void onStream(String partialResponse, boolean isLastChunk) {
                    // 更新最后一条AI消息的内容
                    List<ChatMessage> messages = chatViewModel.getMessages();
                    if (!messages.isEmpty()) {
                        ChatMessage lastMessage = messages.get(messages.size() - 1);
                        if (lastMessage.getType() == ChatMessage.TYPE_AI) {
                            lastMessage.setContent(lastMessage.getContent() + partialResponse);
                            chatViewModel.getMessagesLiveData().setValue(messages);
                        }
                    }
                }

                @Override
                public void onComplete(String fullResponse) {
                    // 发送广播
                    Intent intent = new Intent("com.example.app.AUDIO_TRANSCRIPTION_RESULT");
                    intent.putExtra("transcription_result", result);
                    LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(intent);

                    // 延迟切换到聊天页面，确保广播被处理
                    new Handler().postDelayed(() -> {
                        if (getActivity() instanceof MainActivity) {
                            ((MainActivity) getActivity()).navigateToChat();
                        }
                    }, 500); // 延迟500毫秒
                }

                @Override
                public void onError(String error) {
                    // 添加错误消息
                    ChatMessage errorMessage = new ChatMessage("抱歉，我遇到了一些问题：" + error, ChatMessage.TYPE_AI);
                    chatViewModel.addMessage(errorMessage);

                    // 发送广播
                    Intent intent = new Intent("com.example.app.AUDIO_TRANSCRIPTION_RESULT");
                    intent.putExtra("transcription_result", result);
                    LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(intent);

                    // 延迟切换到聊天页面
                    new Handler().postDelayed(() -> {
                        if (getActivity() instanceof MainActivity) {
                            ((MainActivity) getActivity()).navigateToChat();
                        }
                    }, 500);
                }
            });
        }
    }

    public static short calculateCRC16(int offset, byte[] data) {
        int genpoly = 0xA001;
        int ret = 0xFFFF;
        for (int i = offset; i < data.length; i++) {
            ret = (ret & 0xFFFF) ^ (data[i] & 0xFF);
            for (int index = 0; index < 8; index++) {
                if ((ret & 0x0001) == 1) {
                    ret = (ret >> 1) ^ genpoly;
                } else {
                    ret = ret >> 1;
                }
            }
        }
        return (short) (ret & 0xFFFF);
    }

    /**
     * 发送命令到设备
     *
     * @param buffer 命令数据（不包含cmd和crc16）
     * @return 是否发送成功
     */
    private boolean sendCommand(byte[] buffer) {
        if (bluetoothGatt == null) {
            Log.e(TAG, "设备未连接");
            return false;
        }

        BluetoothGattCharacteristic writeCharacteristic = bluetoothGatt.getService(SERVICE_UUID)
                .getCharacteristic(WRITE_CHAR_UUID);
        if (writeCharacteristic == null) {
            Log.e(TAG, "特征不支持写入操作");
            return false;
        }

        // 统一使用WRITE_TYPE_DEFAULT，因为设备需要返回响应
        writeCharacteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT);

        // 发送指令
        writeCharacteristic.setValue(buffer);
        boolean writeResult = bluetoothGatt.writeCharacteristic(writeCharacteristic);
        Log.i(TAG, "发送指令: " + (writeResult ? "成功" : "失败"));

        return writeResult;
    }

    /**
     * 查询设备DPI
     */
    private void queryDpi() {
        Log.i(TAG, "开始查询DPI");
        
        // 构造数据部分
        byte[] data = new byte[2];
        data[0] = 0x00;  // GET操作
        data[1] = 0x00;  // DPI步进值（查询时设为0）

        // 构造完整命令（命令类型 + CRC16 + 数据）
        byte[] buffer = new byte[data.length + 3];
        buffer[0] = CMD_MOUSE_DPI;  // 命令类型
        System.arraycopy(data, 0, buffer, 3, data.length);

        // 计算CRC16（只计算数据部分）
        short crc = calculateCRC16(0, data);
        buffer[1] = (byte) (crc & 0xFF);
        buffer[2] = (byte) ((crc >> 8) & 0xFF);

        // 打印完整的命令数据
        StringBuilder sb = new StringBuilder();
        for (byte b : buffer) {
            sb.append(String.format("%02X ", b));
        }
        Log.i(TAG, "DPI查询命令数据: " + sb.toString());

        // 添加重试机制
        int maxRetries = 3;
        int retryCount = 0;
        boolean success = false;
        
        while (retryCount < maxRetries && !success) {
            success = sendCommand(buffer);
            if (!success) {
                retryCount++;
                Log.w(TAG, "DPI查询命令发送失败，第" + retryCount + "次重试");
                try {
                    Thread.sleep(1000); // 等待1秒后重试
                } catch (InterruptedException e) {
                    Log.e(TAG, "重试等待被中断", e);
                    break;
                }
            }
        }
        
        Log.i(TAG, "DPI查询命令发送结果: " + (success ? "成功" : "失败"));
    }

    /**
     * 设置设备DPI
     */
    private void setDpi(byte dpiStep) {
        Log.i(TAG, "开始设置DPI，步进值: " + dpiStep);

        // 构造数据部分
        byte[] data = new byte[2];
        data[0] = 0x01;  // SET操作
        data[1] = dpiStep;  // DPI步进值

        // 构造完整命令（命令类型 + CRC16 + 数据）
        byte[] buffer = new byte[data.length + 3];
        buffer[0] = CMD_MOUSE_DPI;  // 命令类型
        System.arraycopy(data, 0, buffer, 3, data.length);

        // 计算CRC16（只计算数据部分）
        short crc = calculateCRC16(0, data);
        buffer[1] = (byte) (crc & 0xFF);
        buffer[2] = (byte) ((crc >> 8) & 0xFF);

        // 打印完整的命令数据
        StringBuilder sb = new StringBuilder();
        for (byte b : buffer) {
            sb.append(String.format("%02X ", b));
        }
        Log.i(TAG, "DPI设置命令数据: " + sb.toString());

        // 发送命令
        if (getActivity() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getActivity();
            if (sendCommand(buffer)) {
            Log.i(TAG, "DPI设置命令已发送");

            // 设置成功后，延迟500ms查询当前DPI值
            new Handler().postDelayed(() -> {
                Log.i(TAG, "开始查询当前DPI值");
                queryDpi();
            }, 500);
            } else {
                Log.e(TAG, "DPI设置命令发送失败");
            }
        }
    }

    /**
     * 同步时间
     */
    private void syncTime() {
        // 构造数据部分
        byte[] data = new byte[23];  // 23字节的padding + 4字节时间戳
        // 填充padding为0
        for (int i = 0; i < 19; i++) {
            data[i] = 0x00;
        }
        // 添加时间戳
        int timestamp = getTimestamp();
        data[19] = (byte) (timestamp & 0xFF);
        data[20] = (byte) ((timestamp >> 8) & 0xFF);
        data[21] = (byte) ((timestamp >> 16) & 0xFF);
        data[22] = (byte) ((timestamp >> 24) & 0xFF);

        // 构造完整命令（命令类型 + CRC16 + 数据）
        byte[] buffer = new byte[data.length + 3];
        buffer[0] = CMD_QUERY_SS;  // 命令类型
        System.arraycopy(data, 0, buffer, 3, data.length);

        // 计算CRC16（只计算数据部分）
        short crc = calculateCRC16(0, data);
        buffer[1] = (byte) (crc & 0xFF);
        buffer[2] = (byte) ((crc >> 8) & 0xFF);

        // 打印完整的命令数据
        StringBuilder sb = new StringBuilder();
        for (byte b : buffer) {
            sb.append(String.format("%02X ", b));
        }
        Log.i(TAG, "同步时间命令数据: " + sb.toString());

        // 发送命令
        if (sendCommand(buffer)) {
            Log.i(TAG, "同步时间命令发送成功");
        } else {
            Log.e(TAG, "同步时间命令发送失败");
        }
    }

    /**
     * 查询设备电量
     * 注意：电量信息在同步时间命令的响应中返回
     */
    private void queryBattery() {
        // 通过同步时间命令获取电量信息
        syncTime();
    }

    /**
     * 获取当前时间戳（秒）
     *
     * @return 从1970年1月1日0点0分0秒起计算的秒数
     */
    private int getTimestamp() {
        int offset = TimeZone.getDefault().getRawOffset();
        long nowSeconds = (System.currentTimeMillis() + offset) / 1000;
        return (int) nowSeconds;
    }


    /**
     * 清除最后连接的设备信息
     */
    private void clearLastConnectedDevice() {
        SharedPreferences prefs = requireContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.remove(PREF_LAST_CONNECTED_DEVICE);
        editor.remove(PREF_LAST_CONNECTED_NAME);
        editor.apply();
        Log.i(TAG, "已清除最后连接的设备信息");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (bluetoothAdapter != null) {
            if (!bluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    if (getActivity() != null &&
                            getActivity().checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT)
                                    == PackageManager.PERMISSION_GRANTED) {
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    }
                } else {
                    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                }
            } else {
                // 如果蓝牙已启用，检查是否需要自动连接
                if (bluetoothGatt == null) {
                    autoConnectLastDevice();
                }
            }
        }
    }

    /**
     * 自动连接上次连接的设备
     */
    private void autoConnectLastDevice() {
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Log.w(TAG, "蓝牙未启用，无法自动连接");
            return;
        }

        SharedPreferences prefs = requireContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String lastAddress = prefs.getString(PREF_LAST_CONNECTED_DEVICE, null);
        String lastName = prefs.getString(PREF_LAST_CONNECTED_NAME, null);

        if (lastAddress != null) {
            Log.i(TAG, "尝试自动连接上次连接的设备: " + lastName + " (" + lastAddress + ")");
            try {
                BluetoothDevice device = bluetoothAdapter.getRemoteDevice(lastAddress);
                if (device != null) {
                    deviceName = lastName;
                    bluetoothGatt = device.connectGatt(getContext(), false, gattCallback);
                    // 更新UI状态
                    if (getActivity() instanceof MainActivity) {
                        ((MainActivity) getActivity()).onConnectionStateChanged(true, deviceName);
                    }
                }
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "无效的MAC地址: " + lastAddress);
                clearLastConnectedDevice();
            }
        }
    }

    /**
     * 开始OTA升级流程：检查新固件版本并下载
     */
    public void startOtaUpgrade() {
        if (!isDeviceConnected()) {
            Log.e(TAG, "设备未连接，无法开始OTA升级");
            Toast.makeText(getContext(), "设备未连接，无法开始OTA升级", Toast.LENGTH_SHORT).show();
            return;
        }

        // 初始化并显示OTA进度对话框
        if (getActivity() != null && !getActivity().isFinishing()) {
            if (mOtaProgressDialog == null) {
                mOtaProgressDialog = new ProgressDialog(getContext());
                mOtaProgressDialog.setTitle("OTA升级");
                mOtaProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mOtaProgressDialog.setMax(100); // 百分比
                mOtaProgressDialog.setIndeterminate(false);
                mOtaProgressDialog.setCancelable(false);
                mOtaProgressDialog.setCanceledOnTouchOutside(false);
            }
            mOtaProgressDialog.setProgress(0);
            mOtaProgressDialog.setMessage("正在准备升级...");
            if (!mOtaProgressDialog.isShowing()) {
                mOtaProgressDialog.show();
            }
        }

        // 下载固件
        downloadFirmware(1); // 使用硬件版本1
    }

    private void downloadFirmware(int hwIndex) {
        String url = OTA_BASE_URL + "/ota/fws/ll/" + hwIndex + ".bin";
        Log.i(TAG, "开始下载固件: " + url);
        // 更新对话框消息
        if (getActivity() != null && !getActivity().isFinishing()) {
            getActivity().runOnUiThread(() -> {
                if (mOtaProgressDialog != null && mOtaProgressDialog.isShowing()) {
                    mOtaProgressDialog.setMessage("正在下载固件...");
                }
            });
        }

        Request request = new Request.Builder()
                .url(url)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.e(TAG, "固件下载失败: " + e.getMessage());
                mainHandler.post(() -> {
                    updateProgress(-1); // 你原有的方法，可能也需要更新UI
                    handleOtaFailure("固件下载失败: " + e.getMessage(), false);
                });
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    ResponseBody body = response.body();
                    if (body != null) {
                        // 获取固件数据
                        byte[] firmwareData = body.bytes();

                        // 计算CRC32校验值
                        long firmwareCrc = calculateCRC32(firmwareData);

                        // 保存固件数据到缓冲区
                        ota_data_len = firmwareData.length;
                        ota_bin_crc = firmwareCrc;
                        ota_data_buff = firmwareData;
                        ota_data_buff_view = ByteBuffer.wrap(firmwareData);

                        Log.i(TAG, String.format("固件下载完成: 大小=%d字节, CRC32=%X",
                                ota_data_len, ota_bin_crc));
                        // 更新对话框
                        if (getActivity() != null && !getActivity().isFinishing()) {
                            getActivity().runOnUiThread(() -> {
                                if (mOtaProgressDialog != null && mOtaProgressDialog.isShowing()) {
                                    mOtaProgressDialog.setMessage("固件下载完成。与设备通信中...");
                                }
                            });
                        }
                        // 开始OTA升级流程
                        doEnableDFU();
                    } else {
                        Log.e(TAG, "固件数据为空");
                        mainHandler.post(() -> {
                            updateProgress(-1);
                            handleOtaFailure("固件数据为空", false);
                        });
                    }
                } else {
                    Log.e(TAG, "固件下载失败: " + response.code());
                    mainHandler.post(() -> {
                        updateProgress(-1);
                        handleOtaFailure("固件下载失败: " + response.code(), false);
                    });
                }
            }
        });
    }

    private void doEnableDFU() {
        Log.i(TAG, "开始使能DFU模式");

        // 构造数据部分（空数据）
        byte[] data = new byte[0];

        // 构造完整命令（命令类型 + CRC16 + 数据）
        byte[] buffer = new byte[data.length + 3];
        buffer[0] = ELPT_OP_ENABLE_DFU_MODE;  // 命令类型
        System.arraycopy(data, 0, buffer, 3, data.length);

        // 计算CRC16（只计算数据部分）
        short crc = calculateCRC16(0, data);
        buffer[1] = (byte) (crc & 0xFF);
        buffer[2] = (byte) ((crc >> 8) & 0xFF);

        // 打印完整的命令数据
        StringBuilder sb = new StringBuilder();
        for (byte b : buffer) {
            sb.append(String.format("%02X ", b));
        }
        Log.i(TAG, "DFU模式使能命令数据: " + sb.toString());

        // 发送命令
        if (sendCommand(buffer)) {
            Log.i(TAG, "发送DFU模式使能命令成功");
        } else {
            Log.e(TAG, "发送DFU模式使能命令失败");
            handleOtaFailure("启用DFU模式失败", true);
        }
    }


    private void doQueryState() {
        Log.i(TAG, "开始查询状态");
        ota_c_state = ELPT_QUERY_SS;

        // 构造数据部分
        byte[] data = new byte[1];
        data[0] = 0x00;  // 查询操作

        // 构造完整命令（命令类型 + CRC16 + 数据）
        byte[] buffer = new byte[data.length + 3];
        buffer[0] = ELPT_QUERY_SS;  // 命令类型
        System.arraycopy(data, 0, buffer, 3, data.length);

        // 计算CRC16（只计算数据部分）
        short crc = calculateCRC16(0, data);
        buffer[1] = (byte) (crc & 0xFF);
        buffer[2] = (byte) ((crc >> 8) & 0xFF);

        // 打印完整的命令数据
        StringBuilder sb = new StringBuilder();
        for (byte b : buffer) {
            sb.append(String.format("%02X ", b));
        }
        Log.i(TAG, "查询状态命令数据: " + sb.toString());

        // 发送命令
        if (sendCommand(buffer)) {
            Log.i(TAG, "发送查询状态命令成功");
        } else {
            Log.e(TAG, "发送查询状态命令失败");
            handleOtaFailure("查询设备状态失败", true);
        }
    }

    private boolean isDeviceConnected() {
        if (getActivity() instanceof MainActivity) {
            MainActivity activity = (MainActivity) getActivity();
            return activity.isDeviceConnected();
        }
        return false;
    }

    private void updateProgress(int progress) {
        if (progress < 0) progress = 0;
        if (progress > 100) progress = 100;
        
        // 更新UI显示进度
        if (connectionStatusText != null) {
            connectionStatusText.setText(String.format("OTA升级进度: %d%%", progress));
        }
    }

    private static final int[] crc32_tab = {
            0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
            0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064,
            0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0,
            0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
            0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
            0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5,
            0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11,
            0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5,
            0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
            0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6,
            0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce,
            0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846,
            0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
            0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
            0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af,
            0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27,
            0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
            0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8,
            0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
            0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0,
            0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
            0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9,
            0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d,
            0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
            0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
            0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a,
            0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a,
            0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02,
            0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
    };

    private long calculateCRC32(byte[] buffer) {
        if (buffer == null || buffer.length == 0) {
            return 0;
        }

        int tb_idx = 0;
        int len = buffer.length;
        long result_crc32_val = 0x33234236;
        result_crc32_val ^= 0xFFFFFFFF;

        for (int i = 0; i < len; i++) {
            result_crc32_val &= 0xFFFFFFFF;
            tb_idx = (int) ((result_crc32_val ^ (buffer[i] & 0xFF)) & 0xFF);
            // 确保tb_idx在有效范围内
            if (tb_idx >= 0 && tb_idx < crc32_tab.length) {
                result_crc32_val = (crc32_tab[tb_idx] ^ ((result_crc32_val >> 8) & 0x00FFFFFF));
            } else {
                Log.e(TAG, "CRC32计算错误：索引越界 tb_idx=" + tb_idx);
                return 0;
            }
        }

        result_crc32_val &= 0xFFFFFFFF;
        result_crc32_val ^= 0xFFFFFFFF;
        result_crc32_val &= 0xFFFFFFFF;
        return result_crc32_val;
    }

    private void doOTAReset() {
        // 构造数据部分
        byte[] data = new byte[19];  // 19字节的数据

        ota_data_offset = 0;

        int fw_ver_num = 1;
        int hw_ver_num = 1;
        long ota_bin_crc32 = ota_bin_crc;
        int ota_bin_size = ota_data_len;

        int offset = 0;
        data[offset++] = (byte) (fw_ver_num & 0xFF);
        data[offset++] = (byte) ((fw_ver_num >> 8) & 0xFF);
        data[offset++] = (byte) ((fw_ver_num >> 16) & 0xFF);
        data[offset++] = (byte) ((fw_ver_num >> 24) & 0xFF);
        data[offset++] = (byte) (hw_ver_num & 0xFF);
        data[offset++] = (byte) ((hw_ver_num >> 8) & 0xFF);
        data[offset++] = (byte) ((hw_ver_num >> 16) & 0xFF);
        data[offset++] = (byte) ((hw_ver_num >> 24) & 0xFF);
        data[offset++] = (byte) (ota_bin_size & 0xFF);
        data[offset++] = (byte) ((ota_bin_size >> 8) & 0xFF);
        data[offset++] = (byte) ((ota_bin_size >> 16) & 0xFF);
        data[offset++] = (byte) ((ota_bin_size >> 24) & 0xFF);
        data[offset++] = (byte) (ota_bin_crc32 & 0xFF);
        data[offset++] = (byte) ((ota_bin_crc32 >> 8) & 0xFF);
        data[offset++] = (byte) ((ota_bin_crc32 >> 16) & 0xFF);
        data[offset++] = (byte) ((ota_bin_crc32 >> 24) & 0xFF);

        // 计算CRC16
        short crc = calculateCRC16(0, data);

        // 构造完整的命令
        byte[] buffer = new byte[data.length + 3];
        buffer[0] = ELPT_OTA_RESET;
        buffer[1] = (byte) (crc & 0xFF);
        buffer[2] = (byte) ((crc >> 8) & 0xFF);
        System.arraycopy(data, 0, buffer, 3, data.length);

        // 发送命令
        if (sendCommand(buffer)) {
            Log.i(TAG, "发送OTA重置命令成功");
        } else {
            Log.e(TAG, "发送OTA重置命令失败");
            handleOtaFailure("OTA重置命令失败", true);
        }
    }

    private void doSendOTAFrame() {
        Log.i(TAG, "开始发送OTA数据帧");
        
        // 计算本次发送的数据大小
        int body_size = fsize - 7; // 头大小
        if ((ota_data_offset + body_size) > ota_data_len) {
            body_size = ota_data_len - ota_data_offset;
        }

        // 构造数据帧
        byte[] buffer = new byte[body_size + 7];
        
        // 1. 设置数据大小和偏移量
        buffer[3] = (byte)(body_size & 0xFF);
        buffer[4] = (byte)(((ota_data_offset & 0x3F) << 2) | ((body_size >> 8) & 0x3));
        buffer[5] = (byte)((ota_data_offset >> 6) & 0xFF);
        buffer[6] = (byte)((ota_data_offset >> 14) & 0xFF);

        // 2. 复制数据内容
        for (int i = 0; i < body_size; i++) {
            buffer[7 + i] = ota_data_buff[ota_data_offset + i];
        }

        // 3. 计算CRC
        short crc = calculateCRC16(3, buffer);

        // 4. 设置命令类型和CRC值
        buffer[0] = ELPT_OTA_PACKET;
        buffer[1] = (byte)(crc & 0xFF);
        buffer[2] = (byte)((crc >> 8) & 0xFF);

        Log.i(TAG, "ota_data_offset: " + ota_data_offset + " size: " + body_size);
        
        // 发送命令
        if (sendCommand(buffer)) {
            Log.i(TAG, "发送OTA数据帧成功");
        } else {
            // Log.e(TAG, "发送OTA数据帧失败"); // 由handleOtaFailure处理日志
            handleOtaFailure("发送OTA数据帧失败", true);
        }
    }

    // OTA失败统一处理
    private void handleOtaFailure(String errorMessage, boolean fromSendCommand) {
        Log.e(TAG, "OTA失败: " + errorMessage + (fromSendCommand ? " (指令发送阶段)" : ""));
        if (getActivity() != null && !getActivity().isFinishing()) {
            getActivity().runOnUiThread(() -> {
                if (mOtaProgressDialog != null && mOtaProgressDialog.isShowing()) {
                    mOtaProgressDialog.setMessage(errorMessage);
                    // 保持对话框显示一段时间以供用户查看错误消息
                    new Handler(Looper.getMainLooper()).postDelayed(() -> {
                        if (mOtaProgressDialog != null && mOtaProgressDialog.isShowing()) {
                            mOtaProgressDialog.dismiss();
                        }
                    }, 2500); // 显示错误2.5秒
                }
            });
        }
        ota_c_state = ELPT_NONE; // 重置OTA状态
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 清理OTA对话框，防止窗口泄漏
        if (mOtaProgressDialog != null) {
            if (mOtaProgressDialog.isShowing()) {
                mOtaProgressDialog.dismiss();
            }
            mOtaProgressDialog = null; // 释放引用
        }
        // 移除Handler的回调，反注册广播接收器等清理工作
        handler.removeCallbacksAndMessages(null);
        mainHandler.removeCallbacksAndMessages(null); // 清理mainHandler的回调
        if (isReceiverRegistered && receiver != null) {
            try {
                requireContext().unregisterReceiver(receiver);
            } catch (IllegalArgumentException e) {
                Log.w(TAG, "Receiver not registered or already unregistered.", e);
            }
            isReceiverRegistered = false;
        }
        // audioTrack.release(); // 确保AudioTrack在这里释放，如果它没有在其他地方更早地释放
        // if (decoder != null) { decoder.close(); } // OpusDecoder是否有close/release方法？
    }

}
